#!/usr/bin/python
# -*- coding: iso-8859-15 -*-

import glob
import os 
import xml.dom.minidom

DATA_FOLDER = '../data/'

series_file = open("series.tsv", "w")
series_file.write("SERIE_KEY\tTITLE\tPUBLISHER\tLICENSER\tSTATUS\tCATEGORY\tNOTE\tLANGUAGE\tUNREVIEWED\tBOOK\n")

issues_file = open("issues.tsv", "w")
issues_file.write("SERIE_KEY\tISSUE_KEY\tTITLE\tURL\tDATE\tPAGES\tPICTURE\tMISSING\tREAD\n")

hashkey = { }
hashkey_missing = { }
hashkey_note = { }

def getText(nodelist):
  rc = []
  for node in nodelist:
    if (node.nodeType == node.TEXT_NODE) or (node.nodeType == node.CDATA_SECTION_NODE):
      rc.append(node.data)
  return ''.join(rc)

def getTextForNode(dom, tagname):
  elements = dom.getElementsByTagName(tagname)
  if (len(elements) == 0):
    return ""
  else:
    return getText(elements[0].childNodes)

def printSerie(serieKey, dom):
  row = [
    serieKey.encode('utf-8'),
    getTextForNode(dom, "title").encode('utf-8'),
    getTextForNode(dom, "publisher").encode('utf-8'),
    getTextForNode(dom, "license").encode('utf-8'),
    getTextForNode(dom, "status").encode('utf-8'),
    getTextForNode(dom, "category").encode('utf-8'),
    hashkey_note.get(serieKey, " ").encode('utf-8'),
    "pt",  # language
    "N",   # unreviewed
    "N"]   # book

  series_file.write("\t".join(row) + "\n")

def printIssue(issueKey, serieKey, dom):
  date_element = dom.getElementsByTagName("date")[0]
  year = date_element.attributes["year"].value
  month = date_element.attributes["month"].value
  date =  year + "/" + month

  row = [
    serieKey.encode('utf-8'),
    issueKey.encode('utf-8'),
    getTextForNode(dom, "subtitle").encode('utf-8'),
    getTextForNode(dom, "url").encode('utf-8'),
    date.encode('utf-8'),
    getTextForNode(dom, "pages").encode('utf-8'),
    " ",  # picture
    hashkey_missing.get(serieKey + "#" + issueKey, "N").encode('utf-8'),
    "N"]  # read

  issues_file.write("\t".join(row) + "\n")

def parseXml(filename):
  serie_key = filename.replace('.xml', '').replace(DATA_FOLDER, '')
  dom = xml.dom.minidom.parseString(open(filename, 'r').read())

  printSerie(serie_key, dom)

  for issueDom in dom.getElementsByTagName("issue"):
    issue_key = issueDom.attributes["number"].value
    printIssue(issue_key, serie_key, issueDom)

def parseBackupXml(filename):
  dom = xml.dom.minidom.parseString(open(filename, 'r').read())

  for serie in dom.getElementsByTagName("serie"):
    serie_key = serie.attributes["key"].value

    note = getTextForNode(serie, "note")
    if note != "":
      hashkey_note[serie_key] = note

    for missing in serie.getElementsByTagName("missing"):
      issue_key = getText(missing.childNodes)
      hashkey_missing[serie_key + "#" + issue_key] = "Y"

parseBackupXml("backup.xml")

for filename in glob.glob( os.path.join(DATA_FOLDER, '*.xml') ):
  parseXml(filename)
